package com.mayikt.edu.controller;

import com.mayikt.edu.base.BaseApiController;
import com.mayikt.edu.base.BaseResponse;
import com.mayikt.edu.domain.EduUser;
import com.mayikt.edu.domain.UserLoginLog;
import com.mayikt.edu.dto.req.LoginReqDto;
import com.mayikt.edu.service.EduUserService;
import com.mayikt.edu.service.UserLoginLogService;
import com.mayikt.edu.utils.MD5Utils;
import com.mayikt.edu.utils.RedisUtils;
import com.mayikt.edu.utils.RquestUtils;
import com.mayikt.edu.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author wangjin
 * @date 2023年10月30日 10:51
 */
@Slf4j
@RestController
public class LoginController extends BaseApiController {
    @Autowired
    private EduUserService eduUserService;
    @Autowired
    private UserLoginLogService userLoginLogService;

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("login")
    public BaseResponse login(@RequestBody LoginReqDto loginReqDto) {
        String userName = loginReqDto.getUserName();
        if (StringUtils.isEmpty(userName)) {
            log.error("[userName is null]");
            return setResultError("userName is null");
        }
        // 查询用户信息
        EduUser dbEduUser = eduUserService.findByUserNameEduUser(userName);
        if (dbEduUser == null) {
            log.error("[未查找到用户信息]");
            return setResultError("账户或者密码错误");
        }
        // 获取用户盐值
        String userSalt = dbEduUser.getUserSalt();
        String newPwd = MD5Utils.md5(loginReqDto.getPassword() + userSalt);
        // 比对数据库密码
        if (!newPwd.equals(dbEduUser.getPassword())) {
            return setResultError("账户或者密码错误");
        }
        // 生产对应的用户token
        String userToken = TokenUtils.getToken();
        Integer userId = dbEduUser.getUserId();
        RedisUtils.setString(userToken, userId);
        HashMap<String, String> result = new HashMap<>();
        result.put("userToken", userToken);
        log.info("用户登录成功 {} ", dbEduUser);
        //记录登录日志
        UserLoginLog userLoginLog = new UserLoginLog(userId,
                RquestUtils.getIpAddr(), userToken, RquestUtils.getEquipment());
        log.info("1,开始记录登录日志： userLoginLog： {} ", userLoginLog);
        userLoginLogService.insert(userLoginLog);
        // addUserLoginLog();
        log.info("3,结束记录登录日志： userLoginLog： {} ", userLoginLog);
        return setResultSuccessData(userToken);
    }

  /*  @Async
    public void addUserLoginLog() {
        try {
            log.info("[2 正在开始记录日志]");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }*/

}
